package com.jtpay.sdk.view;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;

import com.jtpay.sdk.R;
import com.jtpay.sdk.jtpay.utils.PayLogUtil;

public class SettingFragment extends PreferenceFragment {
    PreferenceScreen mPreferenceScreen;
    SharedPreferences mPreferences;
    CheckBoxPreference mCBRememberPassword;
    CheckBoxPreference mCBAutoLogin;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
        initWidgets();
    }

    private void initWidgets() {
        mPreferenceScreen = getPreferenceScreen();

        mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        boolean remember_password = mPreferences.getBoolean(getString(R.string.setting_remember_password), false);
        boolean auto_login = mPreferences.getBoolean(getString(R.string.setting_auto_login), false);
        mCBRememberPassword = (CheckBoxPreference) mPreferenceScreen.findPreference(getString(R.string.setting_remember_password));
        mCBAutoLogin = (CheckBoxPreference) mPreferenceScreen.findPreference(getString(R.string.setting_auto_login));
        PayLogUtil.log("initWidgets remember_password = " + remember_password + " auto_login = " + auto_login);
        mCBAutoLogin.setChecked(auto_login);
        mCBRememberPassword.setChecked(remember_password);

        mCBAutoLogin.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                saveSetting(R.string.setting_auto_login, (boolean) newValue);
                return true;
            }
        });
        mCBRememberPassword.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                saveSetting(R.string.setting_remember_password, (boolean) newValue);
                return true;
            }
        });
    }

    private void saveSetting(int id, boolean value) {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putBoolean(getString(id), value);
        editor.commit();
    }
}
